import $setQuery from 'spore-kit-location/setQuery'

function getTs (sec) {
	sec = sec || 15 * 60
	return Math.floor((new Date()).getTime() / (sec * 1000))
}

function getScript (options) {
	options = options || {}

	let src = options.src || ''
	let charset = options.charset || ''
	let onLoad = options.onLoad || function () {}

	// 用分钟时间戳有限穿透cdn
	src = $setQuery(src, {
		ts: getTs(60)
	})

	let script = document.createElement('script')
	script.async = 'async'
	script.src = src

	if (charset) {
		script.charset = charset
	}
	script.onreadystatechange = function () {
		if (
			!this.readyState ||
			this.readyState === 'loaded' ||
			this.readyState === 'complete'
		) {
			if (typeof onLoad === 'function') {
				onLoad()
			}
			this.onload = null
			this.onreadystatechange = null
			this.parentNode.removeChild(this)
		}
	}
	script.onload = script.onreadystatechange
	document.getElementsByTagName('head')[0].appendChild(script)
	return script
}

export default getScript
